<template>
  <div class="app-page">
    <aside-tree
      title="组织机构"
      :tree-data="treeData"
      :loading="$loadingPlugin.getTreeData"
      @currentChange="currentChange"
      @refresh="getTreeData"
    />
    <div class="content">
      <el-table-form ref="form" :model="query">
        <el-form-item label="编号:" prop="userCode">
          <el-input v-model.trim="query.userCode" :maxlength="11" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="名称:" prop="userName">
          <el-input v-model.trim="query.userName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="电话:" prop="uphone">
          <el-input v-model.trim="query.uphone" clearable @input="query.uphone=query.uphone.replace(/[^0-9]/g,'')" />
        </el-form-item>
        <el-form-item label="类型:" prop="utype">
          <el-select v-model="query.utype" placeholder="请选择" filterable clearable>
            <el-option
              v-for="item in userTypeMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <template v-slot:btns>
          <el-checkbox v-model="checked" style="margin-right: 20px;" @change="checkboxChange">包含下级</el-checkbox>
          <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>
      <div style="margin-bottom: 10px;">
        <el-button v-permission="2" type="primary" icon="el-icon-plus" @click="add">新增用户</el-button>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        :immediate-fetch="false"
        @fetch="fetchData"
      />
    </div>
    <add-user ref="addUser" :tree-data="treeData" :user-type-map="userTypeMap" />
    <edit-role ref="editRole" />
    <reset-pwd ref="resetPwd" />
    <login-history ref="loginHistory" />
  </div>
</template>

<script>
  import AsideTree from './components/AsideTree'
  import AddUser from './components/AddUser'
  import { organizationQueryList, userQueryList, userDelete, queryMap } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { parseTime } from '@/utils'
  import EditRole from './components/EditRole'
  import ResetPwd from './components/ResetPwd'
  import LoginHistory from './components/LoginHistory'

  export default {
    name: 'orgUser',
    components: {
      AsideTree,
      AddUser,
      EditRole,
      ResetPwd,
      LoginHistory
    },
    data() {
      return {
        treeData: [],
        userTypeMap: [],
        currentOrg: null,
        checked: false,
        query: {
          userName: '',
          userCode: '',
          uphone: undefined,
          utype: ''
        },
        tableData: {
          total: 0,
          column: [
            {
              prop: 'userCode',
              label: '编码'
            },
            {
              prop: 'userName',
              label: '名称',
              width: 110
            },
            {
              prop: 'utype',
              label: '类型',
              width: 160,
              showOverflowTooltip: true,
              render: (h, { row }) => {
                if (!row.utype) return ''
                const arr = this.userTypeMap.filter((item, index) => (row.utype >> index) & 1)
                const str = arr.map(i => i.desc).join(',')
                return <span>{str}</span>
              }
            },
            {
              prop: 'uphone',
              label: '电话',
              width: 110
            },
            {
              prop: 'orgName',
              label: '所属机构',
              width: 110
            },
            {
              prop: 'uaddress',
              width: 120,
              label: '地址'
            },
            {
              prop: 'urole',
              width: 170,
              label: '角色'
            },
            {
              prop: 'lastLoginDt',
              width: 170,
              label: '最后登陆时间',
              render: (h, { row }) => <el-link underline={false} onClick={() => this.openLoginHistory(row)}>{ row.lastLoginDt && parseTime(row.lastLoginDt, '{y}-{m}-{d} {h}:{i}:{s}') }</el-link>
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 220,
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link v-permission='3' underline={false} size='mini' onClick={() => this.update(row, $index)}>
                      编辑
                    </el-link>
                    <el-link v-permission='5' underline={false} size='mini' onClick={() => this.editRole(row, $index)}>
                      用户角色
                    </el-link>
                    <el-link v-permission='6' underline={false} type='danger' size='mini' onClick={() => this.resetPwd(row, $index)}>
                      重置密码
                    </el-link>
                    <el-link v-permission='4' underline={false} size='mini' type='danger' onClick={() => this.del(row, $index)}>
                      作废
                    </el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await Promise.all([this.getTreeData(), this.queryOptionsMap()])
    },
    methods: {
      async getTreeData() {
        const res = await organizationQueryList({})
        const data = res.data.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          currentPage,
          pageSize,
          ...this.query
        }
        if (this.checked) {
          query.orgSNNo = this.currentOrg.orgSNNo
        } else {
          query.orgId = this.currentOrg.orgId
        }
        const res = await userQueryList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      currentChange(current) {
        this.currentOrg = current
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await queryMap({ enumName: 'UserType' })
        this.userTypeMap = res.data // 用户类型
      },
      checkboxChange(value) {
        this.checked = value
        this.$refs.lbTable.fetch()
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async add() {
        await this.$refs.addUser.open(null, this.currentOrg)
        this.$refs.lbTable.fetch()
      },
      async update(row, index) {
        await this.$refs.addUser.open(row, this.currentOrg)
        this.$refs.lbTable.fetch()
      },
      // 用户角色
      async editRole(row) {
        await this.$refs.editRole.open(row)
        this.$refs.lbTable.fetch()
      },
      // 重置密码
      async resetPwd(row) {
        await this.$refs.resetPwd.open(row)
        this.$refs.lbTable.fetch()
      },
      del(row, index) {
        this.$confirm('确定删除此用户？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在删除',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          userDelete({ userId: row.userId }).then(() => {
            this.tableData.data.splice(index, 1)
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      // 点击最后登陆时间打开历史登录记录
      async openLoginHistory(row) {
        await this.$refs.loginHistory.open(row)
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  display: flex;
  padding: 0;
  .content {
    width: 0;
    padding: 0 10px 0 10px;
    flex: 1;
  }
}
</style>
